package com.everydayflash.cart.mods {
	import net.hires.debug.Stats;
	
	import com.as3dmod.ModifierStack;
	import com.as3dmod.modifiers.Bend;
	import com.as3dmod.modifiers.Perlin;
	import com.as3dmod.util.bitmap.PerlinNoise;
	import com.everydayflash.cart.core.AbstractSketch;
	import com.everydayflash.cart.core.Pixel3D;
	import com.everydayflash.cart.mods.plugin.LibrarySimple;
	
	import flash.display.BitmapData;
	import flash.display.BitmapDataChannel;
	import flash.events.MouseEvent;
	import flash.geom.Matrix3D;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Vector3D;
	import flash.utils.ByteArray;		

	/**
	 * @author bartekd
	 */
	public class ModBend extends AbstractSketch {
		
		private var pts:Vector.<Pixel3D>;
		
		private var projection:Matrix3D;
		private var matrix:Matrix3D;
		private var stack:ModifierStack;
		private var bend:Bend;
		
		private var iv:Vector3D;
		private var numParticle:int;
		
		private var bytes:ByteArray;

		override protected function init():void {
			addChild(new Stats());
			
			var p:PerspectiveProjection = new PerspectiveProjection();
			p.focalLength = 400;
			projection = p.toMatrix3D();
			matrix = new Matrix3D();

			pts = new Vector.<Pixel3D>();
			
			bytes = new ByteArray();
			bytes.length =  bcanvas.width * bcanvas.height;

			var d:Number = 2.5;
			numParticle = 32000;
			var b:Number = 50;
			for (var i:int = 0; i < numParticle; i++) {
				var r:Pixel3D = new Pixel3D(i / b * d - 800 + Math.random() * 3, 0, i % b * d - 250 + Math.random() * 3);
				r.color = 0xffffff;
				pts.push(r);
			}
			
			stack = new ModifierStack(new LibrarySimple(), pts);
			
			bend = new Bend(1);
			stack.addModifier(bend);
			stack.collapse();
			
			var perlin:Perlin = new Perlin(.5, new PerlinNoise(64,64));
			perlin.speedX = 0;			perlin.speedY = -.5;
			perlin.source.octaves = 2;
			perlin.source.baseX = 16;
			perlin.source.baseY = 16; 
			perlin.source.channels = BitmapDataChannel.GREEN;
			stack.addModifier(perlin);
		}

		override protected function mouseDown(e:MouseEvent):void {
		}

		override protected function draw():void {
			drawFlash();
		}

		private function drawFlash():void {
//			stack.apply();
			bcanvas.lock();
			
			clearBCanvas();
			
			matrix.identity();
			matrix.appendTranslation(0, 100, 350);

			for (var i:int = 0; i < numParticle; i++) {
				iv = matrix.transformVector(pts[i]);
				
				var vz:Number = 1 - (iv.z / 600);
				vz = Math.min(1, vz);
				vz = Math.max(0, vz);
				
				iv = projection.transformVector(iv);
				iv.project();
				bcanvas.setPixel32(sw / 2 + iv.x, sh/2 + iv.y, (vz * 255) << 24 | 0xffffff);
			}
			
			bcanvas.unlock();
		}
	}
}
